import { setup } from "@css-render/vue3-ssr";
import { defineNuxtPlugin } from "#app";
import fs from 'fs';
export default defineNuxtPlugin(nuxtApp => {
    if (process.server) {
        const { collect } = setup(nuxtApp.vueApp);
        const originalRenderMeta:any = nuxtApp.ssrContext?.renderMeta;
        nuxtApp.ssrContext = (nuxtApp.ssrContext as any) || {};
        //解决样式加载缓慢问题
        nuxtApp.ssrContext?.head.hooks.hook('tags:resolve', (ctx) => {
            const styles = collect();
            const regex = /<style[^>]*>([\s\S]*?)<\/style>/g;
            let matches;
            const extractedStyles = [];
            while ((matches = regex.exec(styles)) !== null) {
                extractedStyles.push(matches[1].trim());
            }
            const concatenatedStyles = extractedStyles.join('\n');
            fs.writeFile('assets/css/naive.css', concatenatedStyles, (err) => {
                if (err) {
                    console.error('Error writing CSS file:', err);
                }
            });
        })

        nuxtApp.ssrContext!.renderMeta = () => {
            if (!originalRenderMeta) {
                return {
                    headTags: collect()
                };
            }
            const originalMeta = originalRenderMeta();
            if ("then" in originalMeta) {
                return originalMeta.then((resolvedOriginalMeta: any) => {
                    return {
                        ...resolvedOriginalMeta,
                        headTags: resolvedOriginalMeta.headTags + collect()
                    };
                });
            } else {
                return {
                    ...originalMeta,
                    headTags: originalMeta.headTags + collect()
                };
            }
        };

    }
});